from flask import Flask, render_template, request, redirect, url_for, flash, jsonify
from werkzeug.utils import secure_filename
from flask_sqlalchemy import SQLAlchemy
import os
from cgdataset import CgDataSet
import matplotlib.pyplot as plt
from predict import data_predict
import cv2

app = Flask(__name__)
app.config['SECRET_KEY'] = 'dev'
# 配置数据库信息
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:dch20001121@localhost:5432/cg'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)
# db.init_app(app)


#设置允许的文件格式
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'JPG', 'PNG', 'bmp'])

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS

class User_information(db.Model):  # 表名将会是 user（自动生成，小写处理）
    id = db.Column(db.Integer, primary_key=True)  # 主键
    name = db.Column(db.String(20))  # 名字
    pwd = db.Column(db.String(30))

@app.route('/upload/analysis', methods=['POST', 'GET'])
def analysis():
    if request.method == 'POST':
        f = request.files['file']
    if not (f and allowed_file(f.filename)):
        return jsonify({"error": 1001, "msg": "请检查上传的图片类型，仅限于png、PNG、jpg、JPG、bmp"})
    upload_path = os.path.join('static/images', f.filename)      
    upload_path = upload_path.replace('\\', '/')
    f.save(upload_path)
    print(upload_path)
    # print(upload_path)
    result = data_predict(upload_path)
    
    return render_template('upload_ok.html', result=result)

@app.route('/upload')  # 添加路由
def upload():
    return render_template('upload.html')

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        name = request.form['user_name']
        pwd = request.form['pwd']
        user1 = User_information.query.first()
        if name == user1.name and pwd == user1.pwd:
            return redirect(url_for('upload'))
        else:
            # flash('Invalid input.')  # 显示错误提示
            return redirect(url_for('index'))
    return render_template('login.html')

if __name__ == "__main__":
    app.run(debug=True, threaded=True)
